package org.telegram.bot.utils;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.utils.StringUtils;
import org.springframework.util.CollectionUtils;
import org.telegram.telegrambots.meta.api.objects.MessageEntity;
import org.telegram.telegrambots.meta.api.objects.User;
import org.telegram.telegrambots.meta.api.objects.replykeyboard.InlineKeyboardMarkup;
import org.telegram.telegrambots.meta.api.objects.replykeyboard.buttons.InlineKeyboardButton;
import org.telegram.telegrambots.meta.api.objects.replykeyboard.buttons.InlineKeyboardRow;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @Author: wyx
 * @Date: 2023/5/28 0:11
 */
public class BotUtil {
    
    public static String concat(String... value){

        if(value!=null && !CollectionUtils.isEmpty(Arrays.asList(value))){
            return StringUtils.join(value,",");
        }
        return "";
    }

    /**
     * 封装@人信息
     * @param originalUser
     * @return
     */
    public static MessageEntity atMessageEntity(User originalUser){
        User temp = BeanUtil.toBean(originalUser,User.class);
        int length = "@".length();
        if(StringUtils.isNotEmpty(originalUser.getUserName())){
            length += originalUser.getUserName().length();
            originalUser.setUserName(originalUser.getUserName());
        }
        else{
            length+=originalUser.getId().toString().length();
            originalUser.setUserName(originalUser.getId().toString());
        }
        return MessageEntity.builder()
                .user(temp)
                .type("text_mention")
                .offset(0)
                .length(length)
                .build();
    }
    
    /**
     * 创建菜单按钮
     * @param btnList
     * @return
     */
    public static InlineKeyboardMarkup generatorKeyboard(JSONArray btnList){
        //总行数按钮
        List<InlineKeyboardRow> keyboard = new ArrayList<>();
        
        for (Object o : btnList) {
            //一行的按钮
            InlineKeyboardRow rowButtons = new InlineKeyboardRow();
            JSONArray rowArray = (JSONArray)o;
            for (Object collArray : rowArray) {
                JSONObject coll = (JSONObject)collArray;
                rowButtons.add(InlineKeyboardButton.builder().text(coll.getString("text")).url(coll.getString("url")).build());
            }
            //构成完整按钮
            keyboard.add(rowButtons);
        }
        //将全部按钮装箱
        return InlineKeyboardMarkup.builder().keyboard(keyboard).build();
    }
}
